const Controller = require('egg').Controller;

class DeepSeekController extends Controller {
  async chat() {
    const { ctx } = this;
    const { model, conversation_id} = ctx.request.body;
    try {
      // 设置响应头，支持流式响应
      ctx.set({
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
      });
      let messages = await this.ctx.model.Message.findAll({
          where: {
            conversation_id
          },
          order: [
              ['create_time', 'ASC']
          ],
          raw: true
      })
      messages = messages.map(item => {
        return {
          role: item.role,
          content: item.content || '',
          reasoning: item.reasoning || '',
          answer: item.answer || ''
        }
      })
      console.log('messages',model)
      let stream = null
      if (model.includes('gpt')) {
        stream = await ctx.service.openai302.chatCompletion(messages, model);
      } else {
        stream = await ctx.service.deepseek.chatCompletion(messages, model);
      }

      for await (const chunk of stream) {
        if (!chunk.choices?.length) {
          console.log('No choices in chunk');
          continue;
        }

        const delta = chunk.choices[0].delta;

        const response = {
          type: delta.reasoning_content ? 'reasoning' : 'answer',
          content: delta.reasoning_content || delta.content || ''
        };

        // 发送数据
        ctx.res.write(`data: ${JSON.stringify(response)}\n\n`);
      }

      // 结束响应
      ctx.res.end();

    } catch (error) {
      console.log(error);
      let errorMessage = error.message;
      let statusCode = error.status || 500;

      // 处理常见错误
      switch (error.code || error.type) {
        case 'ETIMEDOUT':
        case 'ESOCKETTIMEDOUT':
        case 'timeout_error':
          errorMessage = '请求超时，请稍后再试';
          statusCode = 504;
          break;
        case 'ECONNREFUSED':
        case 'connection_error':
          errorMessage = '无法连接到 DeepSeek 服务，请检查网络';
          statusCode = 503;
          break;
        case 'rate_limit_error':
          errorMessage = '请求频率超限，请稍后再试';
          statusCode = 429;
          break;
        case 'invalid_request_error':
          errorMessage = '请求参数错误';
          statusCode = 400;
          break;
        case 'authentication_error':
          errorMessage = 'API 认证失败，请检查配置';
          statusCode = 401;
          break;
      }

      ctx.status = statusCode;
      ctx.body = {
        success: false,
        error: errorMessage,
        details: process.env.NODE_ENV === 'development' ? {
          code: error.code,
          type: error.type,
          response: error.response?.data
        } : null
      };
    }
  }
}

module.exports = DeepSeekController;
